package com.xl.utils.util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;


/**
 * @Author xionglin
 * @Classname WatermarkUtil
 * @Description 水印工具类
 * @Date 2019/9/20 15:49
 */
@Slf4j
public class WatermarkUtil {
    /**
     * 水印的实现思路
     * 1.创建缓存图片对象
     * 2.创建Java绘图工具对象
     * 3.使用绘图工具对象将原图绘制到缓存图片对象
     * 4.使用绘图工具将水印（文字/图片）绘制到缓存图片对象
     * 5.创建图像编码工具类
     * 6.使用图片编码工具类，输出缓存图像到目标图片文件
     */

    /**
     * 水印文字
     */

    public static final String MARK_TEXT="曲终人散";

    /**
     * 字体
     */
    public static final String FONT_NAME="微软雅黑";

    /**
     * 字体样式
     */
    public static final int FONT_STYLE= Font.BOLD;

    /**
     * 字体大小 单位像素
     */
    public static final int FONT_SIZE=100;

    /**
     * 文字颜色
     */
    public static final Color FONT_COLOR=Color.BLACK;

    /**
     * 文字水印透明度 30%
     */
    public static float ALPHA=0.3F;

    /**
     * 绘制位置横坐标
     */
    public static final int X=120;

    /**
     * 绘制位置纵坐标
     */
    public static final int Y=120;

    /**
     *
     */
    public static final String  BASE_PATH="C:\\tempDir\\";

    /**
     * 水印图片地址
     */
    public static final String  MARK_LOGO_IMAGE="C:\\tempDir\\logo.png";

    /**
     * 处理后输出图片的格式
     */
    public static final String  FORMAT_NAME="jpg";


    /**
     * 添加单条文字水印
     * @param myFile
     * @param imageFileName
     * @return
     */
    public String textWaterMark(MultipartFile myFile, String imageFileName) {
        int X = 636;
        int Y = 700;

        try {
            Image image = ImageIO.read(myFile.getInputStream());
            //计算原始图片宽度长度
            int width = image.getWidth(null);
            int height = image.getHeight(null);
            //创建图片缓存对象
            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            //创建java绘图工具对象
            Graphics2D graphics2d = bufferedImage.createGraphics();
            //参数主要是，原图，坐标，宽高
            graphics2d.drawImage(image, 0, 0, width, height, null);
            graphics2d.setFont(new Font(FONT_NAME, FONT_STYLE, FONT_SIZE));
            graphics2d.setColor(FONT_COLOR);

            //使用绘图工具将水印绘制到图片上
            //计算文字水印宽高值
            int waterWidth = FONT_SIZE*getTextLength(MARK_TEXT);
            int waterHeight = FONT_SIZE;
            //计算水印与原图高宽差
            int widthDiff = width-waterWidth;
            int heightDiff = height-waterHeight;
            //水印坐标设置
            if (X > widthDiff) {
                X = widthDiff;
            }
            if (Y > heightDiff) {
                Y = heightDiff;
            }
            //水印透明设置
            graphics2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, ALPHA));
            graphics2d.drawString(MARK_TEXT, X, Y+FONT_SIZE);

            graphics2d.dispose();
            OutputStream os = new FileOutputStream(BASE_PATH+"/"+imageFileName);
            ImageIO.write(bufferedImage, FORMAT_NAME, os);
            close(os);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return "success";
    }



    /**
     * 添加单图片水印
     * @param myFile
     * @param imageFileName
     * @param request
     * @return
     */
    public String imageWaterMark(MultipartFile myFile, String imageFileName, HttpServletRequest request) {
        OutputStream os;
        int X = 636;
        int Y = 763;

        try {
            Image image = ImageIO.read(myFile.getInputStream());
            //计算原始图片宽度长度
            int width = image.getWidth(null);
            int height = image.getHeight(null);
            //创建图片缓存对象
            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            //创建java绘图工具对象
            Graphics2D graphics2d = bufferedImage.createGraphics();
            //参数主要是，原图，坐标，宽高
            graphics2d.drawImage(image, 0, 0, width, height, null);
            graphics2d.setFont(new Font(FONT_NAME, FONT_STYLE, FONT_SIZE));
            graphics2d.setColor(FONT_COLOR);

            //水印图片路径
            String logoPath = MARK_LOGO_IMAGE;
            File logo = new File(logoPath);
            Image imageLogo = ImageIO.read(logo);
            int widthLogo = imageLogo.getWidth(null);
            int heightLogo = imageLogo.getHeight(null);
            int widthDiff = width-widthLogo;
            int heightDiff = height-heightLogo;
            //水印坐标设置
            if (X > widthDiff) {
                X = widthDiff;
            }
            if (Y > heightDiff) {
                Y = heightDiff;
            }
            //水印透明设置
            graphics2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, ALPHA));
            graphics2d.drawImage(imageLogo, X, Y, null);
            //释放工具
            graphics2d.dispose();
            os = new FileOutputStream(BASE_PATH+"/"+imageFileName);
            //使用图像编码工具类，输出缓存图像到目标文件
            ImageIO.write(bufferedImage, FORMAT_NAME, os);
            close(os);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return "success";
    }


    /**
     * 添加多条文字水印
     * @param myFile
     * @param imageFileName
     * @return
     */
    public String moreTextWaterMark(MultipartFile myFile,String imageFileName) {
        int X = 636;
        int Y = 763;

        try {
            Image image = ImageIO.read(myFile.getInputStream());
            //计算原始图片宽度长度
            int width = image.getWidth(null);
            int height = image.getHeight(null);
            //创建图片缓存对象
            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            //创建java绘图工具对象
            Graphics2D graphics2d = bufferedImage.createGraphics();
            //参数主要是，原图，坐标，宽高
            graphics2d.drawImage(image, 0, 0, width, height, null);
            graphics2d.setFont(new Font(FONT_NAME, FONT_STYLE, FONT_SIZE));
            graphics2d.setColor(FONT_COLOR);

            //使用绘图工具将水印绘制到图片上
            //计算文字水印宽高值
            int waterWidth = FONT_SIZE*getTextLength(MARK_TEXT);
            int waterHeight = FONT_SIZE;

            //水印透明设置
            graphics2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, ALPHA));
            graphics2d.rotate(Math.toRadians(30), bufferedImage.getWidth()/2, bufferedImage.getHeight()/2);

            int x = -width/2;
            int y = -height/2;

            while(x < width*1.5){
                y = -height/2;
                while(y < height*1.5){
                    graphics2d.drawString(MARK_TEXT, x, y);
                    y+=waterHeight+100;
                }
                x+=waterWidth+100;
            }
            graphics2d.dispose();

            OutputStream os = new FileOutputStream(BASE_PATH+"/"+imageFileName);
            ImageIO.write(bufferedImage,FORMAT_NAME,os);
            close(os);
        } catch (IOException e) {
            log.error("异常",e.getMessage());
        }
        return "success";
    }


    /**
     * 多图片水印
     * @param myFile
     * @param imageFileName
     * @param request
     * @return
     */
    public String moreImageWaterMark(MultipartFile myFile,String imageFileName,HttpServletRequest request) {
        int X = 636;
        int Y = 763;

        try {
            Image image = ImageIO.read(myFile.getInputStream());
            //计算原始图片宽度长度
            int width = image.getWidth(null);
            int height = image.getHeight(null);
            //创建图片缓存对象
            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            //创建java绘图工具对象
            Graphics2D graphics2d = bufferedImage.createGraphics();
            //参数主要是，原图，坐标，宽高
            graphics2d.drawImage(image, 0, 0, width, height, null);
            graphics2d.setFont(new Font(FONT_NAME, FONT_STYLE, FONT_SIZE));
            graphics2d.setColor(FONT_COLOR);

            //水印图片路径
            String logoPath = "/img/logo.png";
            String realPath = request.getSession().getServletContext().getRealPath(logoPath);
            File logo = new File(realPath);
            Image imageLogo = ImageIO.read(logo);
            int widthLogo = imageLogo.getWidth(null);
            int heightLogo = imageLogo.getHeight(null);

            //水印透明设置
            graphics2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, ALPHA));

            graphics2d.rotate(Math.toRadians(30), bufferedImage.getWidth()/2, bufferedImage.getHeight()/2);

            int x = -width/2;
            int y;

            while(x < width*1.5){
                y = -height/2;
                while(y < height*1.5){
                    graphics2d.drawImage(imageLogo, x, y, null);
                    y+=heightLogo+100;
                }
                x+=widthLogo+100;
            }
            graphics2d.dispose();
            OutputStream os = new FileOutputStream(BASE_PATH+"/"+imageFileName);
            ImageIO.write(bufferedImage,FORMAT_NAME,os);
            close(os);
        } catch (IOException e) {
            log.error("异常",e.getMessage());
        }
        return "success";
    }

    /**
     * 计算水印文本长度
     * 1、中文长度即文本长度
     * 2、英文长度为文本长度二分之一
     * @param text
     * @return
     */
    public int getTextLength(String text){
        if(null == text || "".equals(text)){
            throw new RuntimeException("水印文本长度不能为空");
        }
        //水印文字长度
        int length = text.length();

        for (int i = 0; i < text.length(); i++) {
            String s =String.valueOf(text.charAt(i));
            if (s.getBytes().length>1) {
                length++;
            }
        }
        return length%2==0?length/2:length/2+1;
    }

    /**
     * 释放资源
     * @param os
     */
    private void close(OutputStream os){
        if(os != null){
            try {
                os.flush();
                os.close();
            } catch (IOException e) {
               log.error("释放资源异常",e.getMessage());
            }
        }
    }

    /**
     * 私有化构成器避免工具类被实例化
     */
    private WatermarkUtil(){}

}
